package com.sec.android.app.myfiles.dialog;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.sec.android.app.myfiles.R;
import com.sec.android.app.myfiles.activity.AbsMyFilesActivity;
import com.sec.android.app.myfiles.activity.FolderSelectorBottomSheetActivity;
import com.sec.android.app.myfiles.log.SamsungAnalyticsLog;
import com.sec.android.app.myfiles.navigation.NavigationInfo;
import com.sec.android.app.myfiles.navigation.NavigationManager;

import static com.sec.android.app.myfiles.activity.FolderSelectorBottomSheetActivity.EXTRA_KEY_PREV_SCREEN_PATH;

/**
 * <pre>
 * Dialog class for ask to user delete or not.
 * Response Activity.RESULT_OK or Activity.RESULT_CANCELED
 * </pre>
 *
 * @author jae.bae
 */
public class ConfirmDeleteDialog extends AbsDialogFragment {

    private static final String ARGS_PLURALS_TITLE_RES_ID = "args_plurals_title";
    private static final String ARGS_TITLE_RES_ID = "args_title";
    private static final String ARGS_MESSAGE_RES_ID = "args_message";
    private static final String ARGS_PLURALS_MESSAGE_RES_ID = "args_plurals_message";
    private static final String ARGS_TARGET_COUNT = "args_target_count";
    private static final String ARGS_TARGET_CHILD_COUNT = "args_target_child_count";
    private static final String ARGS_TARGET_PATH = "args_target_path";
    private static final String ARGS_TARGET_CATEGORY_PATH = "args_target_category_path";
    private static final String ARGS_TARGET_CATEGORY_BUCKET_ID = "args_target_category_bucket_id";
    private static final String ARGS_POSITIVE_BTN_TEXT = "args_positive_btn_text";
    private static final String ARGS_NEGATIVE_BTN_TEXT = "args_negative_btn_text";
    public static final String ARGS_CONFIRM_CODE = "args_confirm_code";

    public static final String ARGS_IS_CLOUD = "args_is_cloud";
    public static final String ARGS_CLOUD_DEVICE_ID = "args_cloud_deviceId";
    public static final String ARGS_CLOUD_PARENT_ID = "args_cloud_parentId";
    public static final String ARGS_CLOUD_FILE_ID = "args_cloud_fileId";
    public static final String ARGS_CLOUD_BUNDLE = "args_cloud_bundle";

    private View mCustomView;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    @Override
    protected Dialog _createDialog() {
        Bundle args = getArguments();
        String title = getTitle(args);
        String message = getMessage(args);
        Intent intent = getActivity().getIntent();
        int previousScreenPath = (intent != null) ? intent.getIntExtra(EXTRA_KEY_PREV_SCREEN_PATH, -1) : -1;
        final long targetCountForDelete = (long) args.getInt(ARGS_TARGET_COUNT);

        int positiveBtnText = args.getInt(ARGS_POSITIVE_BTN_TEXT);
        if (positiveBtnText == 0) {
            positiveBtnText = R.string.menu_delete;
        }
        int negativeBtnText = args.getInt(ARGS_NEGATIVE_BTN_TEXT);
        if (negativeBtnText == 0) {
            negativeBtnText = R.string.cancel;
        }

        SamsungAnalyticsLog.ScreenPath screenPath = null;
        if (previousScreenPath != -1 && getActivity() instanceof FolderSelectorBottomSheetActivity) {
            if (previousScreenPath == SamsungAnalyticsLog.ScreenPath.GET_MORE_SPACE_LARGE.getCode()) {
                screenPath = SamsungAnalyticsLog.ScreenPath.GET_MORE_SPACE_LARGE_BACK_UP;
            } else if (previousScreenPath == SamsungAnalyticsLog.ScreenPath.GET_MORE_SPACE_UNUSED.getCode()) {
                screenPath = SamsungAnalyticsLog.ScreenPath.GET_MORE_SPACE_UNUSED_BACK_UP;
            }
        } else {
            NavigationManager navigationMgr = NavigationManager.getInstance(((AbsMyFilesActivity) getActivity()).getProcessId());
            NavigationInfo curInfo = navigationMgr.getCurInfo();
            if (curInfo != null) {
                screenPath = curInfo.getScreenPath();
            }
        }
        final SamsungAnalyticsLog.ScreenPath baseScreenPath = SamsungAnalyticsLog.setGetMoreSpaceScreenPath(screenPath);

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        if (!TextUtils.isEmpty(title)) {
            builder.setTitle(title);
        }

        if (mCustomView != null) {
            builder.setView(mCustomView);
        } else {
            builder.setMessage(message);
        }

        builder.setPositiveButton(positiveBtnText, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                getTargetFragment().onActivityResult(getTargetRequestCode(),
                        Activity.RESULT_OK, getResultIntent());
                dialog.dismiss();
                if (SamsungAnalyticsLog.isGetMoreSpaceDeleteScreenPath(baseScreenPath)) {
                    SamsungAnalyticsLog.sendLog(baseScreenPath, SamsungAnalyticsLog.Event.DELETE, targetCountForDelete, null);
                } else {
                    SamsungAnalyticsLog.sendLog(SamsungAnalyticsLog.ScreenPath.DELETE_POPUP, SamsungAnalyticsLog.Event.DELETE, null);
                }
            }
        }).setNegativeButton(negativeBtnText, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                getTargetFragment().onActivityResult(getTargetRequestCode(),
                        Activity.RESULT_CANCELED, getResultIntent());
                dialog.dismiss();
                if (SamsungAnalyticsLog.isGetMoreSpaceDeleteScreenPath(baseScreenPath)) {
                    SamsungAnalyticsLog.sendLog(baseScreenPath, SamsungAnalyticsLog.Event.CANCEL, null);
                } else {
                    SamsungAnalyticsLog.sendLog(SamsungAnalyticsLog.ScreenPath.DELETE_POPUP, SamsungAnalyticsLog.Event.CANCEL, null);
                }
            }
        });
        return builder.create();
    }

    private Intent getResultIntent() {
        Intent ret = null;
        Bundle args = getArguments();
        if (args != null) {
            if (args.containsKey(ARGS_CONFIRM_CODE)) {
                ret = new Intent();
                ret.putExtra(ARGS_CONFIRM_CODE, args.getInt(ARGS_CONFIRM_CODE));
            }
            if (args.containsKey(ARGS_TARGET_PATH)) {
                if (ret == null) {
                    ret = new Intent();
                }
                ret.putExtra("targetPath", args.getString(ARGS_TARGET_PATH));
                ret.putExtra(ARGS_IS_CLOUD, args.getBoolean(ARGS_IS_CLOUD));
                ret.putExtra(ARGS_CLOUD_BUNDLE, args.getBundle(ARGS_CLOUD_BUNDLE));
                if (args.containsKey(ARGS_TARGET_CATEGORY_PATH) && args.containsKey(ARGS_TARGET_CATEGORY_BUCKET_ID)) {
                    ret.putExtra("targetCategoryPath", args.getString(ARGS_TARGET_CATEGORY_PATH));
                    ret.putExtra("targetCategoryBucketId", args.getString(ARGS_TARGET_CATEGORY_BUCKET_ID));
                }
            }
            // For SA
            if (args.containsKey(ARGS_TARGET_COUNT)) {
                if (ret == null) {
                    ret = new Intent();
                }
                ret.putExtra("targetCount", args.getInt(ARGS_TARGET_COUNT));
            }
        }
        return ret;
    }

    private String getTitle(Bundle args) {
        String title = null;
        int count = args.getInt(ARGS_TARGET_COUNT);
        int pluralsTitleId = args.getInt(ARGS_PLURALS_TITLE_RES_ID);
        int titleId = args.getInt(ARGS_TITLE_RES_ID);
        if (titleId != 0) {
            title = getResources().getString(titleId);
        } else if (pluralsTitleId != 0) {
            title = getResources().getQuantityString(pluralsTitleId, count, count);
        }
        return title;
    }

    private String getMessage(Bundle args) {
        String message = "";
        int targetCount = args.getInt(ARGS_TARGET_COUNT);
        int targetChildCount = args.getInt(ARGS_TARGET_CHILD_COUNT);
        int msgId = args.getInt(ARGS_MESSAGE_RES_ID);
        int pluralsMsgId = args.getInt(ARGS_PLURALS_MESSAGE_RES_ID);
        if (msgId != 0) {
            message = getString(msgId);
        } else {
            if (pluralsMsgId != 0) {
                if (targetChildCount == 0) {
                    message = getResources().getQuantityString(pluralsMsgId, targetCount, targetCount);
                } else {
                    if (pluralsMsgId == R.plurals.n_delete_folder_and_files_in_it) {
                        message = getResources().getQuantityString(pluralsMsgId, targetChildCount, targetChildCount);
                    } else if (pluralsMsgId == R.plurals.n_delete_folders_and_files_in_it) {
                        message = getResources().getQuantityString(pluralsMsgId, targetCount, targetCount, targetChildCount);
                    }
                }
            } else {
                message = getResources().getQuantityString(R.plurals.delete_item_num, targetCount, targetCount);
            }
        }
        return message;
    }

    private void setCustomView(View customView) {
        mCustomView = customView;
    }


    public static class Builder {
        Bundle mArgs;
        View mCustomView;

        public Builder() {
            mArgs = new Bundle();
        }

        public ConfirmDeleteDialog build() {
            ConfirmDeleteDialog dialog = new ConfirmDeleteDialog();
            dialog.setArguments(new Bundle(mArgs));
            dialog.setCustomView(mCustomView);
            return dialog;
        }

        public Builder setTitle(int resId) {
            mArgs.putInt(ARGS_TITLE_RES_ID, resId);
            return this;
        }

        public Builder setPluralsTitle(int resId) {
            mArgs.putInt(ARGS_PLURALS_TITLE_RES_ID, resId);
            return this;
        }

        public Builder setMessage(int resId) {
            mArgs.putInt(ARGS_MESSAGE_RES_ID, resId);
            return this;
        }

        public Builder setPluralsMessage(int resId) {
            mArgs.putInt(ARGS_PLURALS_MESSAGE_RES_ID, resId);
            return this;
        }

        public Builder setTargetPath(String path) {
            mArgs.putString(ARGS_TARGET_PATH, path);
            return this;
        }

        public Builder setIsCloud(boolean isCloud, int deviceId, String parentId, String fileId) {
            mArgs.putBoolean(ARGS_IS_CLOUD, isCloud);
            if (isCloud) {
                Bundle cloudBundle = new Bundle();
                cloudBundle.putInt(ARGS_CLOUD_DEVICE_ID, deviceId);
                cloudBundle.putString(ARGS_CLOUD_PARENT_ID, parentId);
                cloudBundle.putString(ARGS_CLOUD_FILE_ID, fileId);

                mArgs.putBundle(ARGS_CLOUD_BUNDLE, cloudBundle);
            }
            return this;
        }

        public Builder setTargetCount(int count) {
            mArgs.putInt(ARGS_TARGET_COUNT, count);
            return this;
        }

        public Builder setTargetChildCount(int count) {
            mArgs.putInt(ARGS_TARGET_CHILD_COUNT, count);
            return this;
        }

        public Builder setConfirmCode(int code) {
            mArgs.putInt(ARGS_CONFIRM_CODE, code);
            return this;
        }

        public Builder setTargetCategoryPath(String categoryPath) {
            mArgs.putString(ARGS_TARGET_CATEGORY_PATH, categoryPath);
            return this;
        }

        public Builder setTargetCategoryBucketId(String bucketId) {
            mArgs.putString(ARGS_TARGET_CATEGORY_BUCKET_ID, bucketId);
            return this;
        }

        public Builder setCustomView(View view) {
            mCustomView = view;
            return this;
        }
    }
}